package com.winit.uCloud.web;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.base.beans.LoginUser;
import com.winit.common.base.web.BaseController;
import com.winit.common.filter.UserInfoUtil;
import com.winit.common.util.HttpClientUtil;
import com.winit.uCloud.manager.UCloudCManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangjian on 16/10/28.
 */
@RestController
@RequestMapping("/uCloud")
public class UCloudCController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(UCloudCController.class);

    @Autowired
    private UCloudCManager uCloudCManager;

    /**
     * 向c环境ogg客户端发送get请求
     *
     * @param request
     * @return
     */
    @RequestMapping("/Cget")
    @ResponseBody
    public JSONObject Cget(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudController.Cget,获取用户信息为空");
            json.put("code", "1");
            json.put("desc", "获取用户登录信息为空");
            return json;
        }

        StringBuffer getUrl = new StringBuffer();

        String url = request.getParameter("url");
        Assert.hasText(url, "com.winit.uCloud.web.UCloudCController.Cget,url为空");

        getUrl.append(url);

        Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            if ("url".equals(paraName)) {
                continue;
            }
            if (getUrl.toString().contains("?")) {
                getUrl.append("&").append(paraName).append("=").append(request.getParameter(paraName));
            } else {
                getUrl.append("?").append(paraName).append("=").append(request.getParameter(paraName));
            }
        }

        try {
            json = HttpClientUtil.doGetForJson(getUrl.toString());
        } catch (Exception e) {
            logger.error("com.winit.uCloud.web.UCloudCController.Cpost 异常", e);
            json.put("code", "1");
            json.put("desc", "请求ucloud客户端异常." + e.getMessage());
        }
        return json;
    }

    /**
     * 查询ogg同步数据量
     *
     * @param request
     * @return
     */
    @RequestMapping("/ogg/total")
    @ResponseBody
    public JSONObject Total(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudController.Total,获取用户信息为空");
            json.put("code", "1");
            json.put("message", "获取用户登录信息为空");
            return json;
        }

        String ip = request.getParameter("ip");
        String url = request.getParameter("url");
        Assert.hasText(ip, "com.winit.uCloud.web.UCloudCController.Total,ip为空");
        Assert.hasText(url, "com.winit.uCloud.web.UCloudCController.Total,url为空");

        try {
            json = uCloudCManager.getTotal(url, ip);
        } catch (Exception e) {
            logger.error("com.winit.uCloud.web.UCloudCController.Total 异常", e);
            json.put("code", "1");
            json.put("message", "获取ogg同步数据量异常." + e.getMessage());
        }
        logger.info("com.winit.uCloud.web.UCloudCController.Total rtn:" + json);
        return json;
    }

    /**
     * 清空redis缓存
     *
     * @param request
     * @return
     */
    @RequestMapping("/ogg/clean")
    @ResponseBody
    public JSONObject CleanReadis(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String ip = request.getParameter("ip");
        Assert.hasText(ip, "com.winit.uCloud.web.UCloudCController.CleanReadis,ip为空");

        try {
            List<JSONObject> list = uCloudCManager.cleanRedis(ip);
            json.put("code", "0");
            json.put("data", list);
        } catch (Exception e) {
            logger.error("com.winit.uCloud.web.UCloudCController.CleanReadis 异常 ip=" + ip, e);
            json.put("code", "1");
            json.put("message", "清空redis缓存异常 ." + e.getMessage());
        }
        logger.info("com.winit.uCloud.web.UCloudCController.CleanReadis rtn:" + json);
        return json;
    }

    /**
     * 下载ogg同步信息文件
     *
     * @param request
     * @param response
     */
    @RequestMapping("/ogg/download")
    @ResponseBody
    public void Download(HttpServletRequest request, HttpServletResponse response) {
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudCController.Download 用户信息为空");
            return;
        }

        String ip = request.getParameter("ip");
        Assert.hasText(ip, "com.winit.uCloud.web.UCloudCController.Download,ip为空");
        String fileName = request.getParameter("fileName");
        if (StringUtils.isEmpty(fileName)) {
            fileName = "c.log";
        }

        InputStream inputStream = null;
        OutputStream os = null;
        String filePath = "/usr/local/Beetle/temp/" + fileName;
        File file = new File(filePath);

        try {
            uCloudCManager.getOggLogFile(ip, fileName);

            if (!file.exists()) {
                logger.error("com.winit.uCloud.web.UCloudCController.Download 从目标端拷贝文件失败 ip=" + ip);
                return;
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            inputStream = new FileInputStream(new File(filePath));
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

        } catch (Exception e) {
            logger.error("com.winit.uCloud.web.UCloudCController.Download 异常 ip=" + ip, e);
            return;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 在ogg目标端执行命令
     *
     * @param request
     * @return
     */
    @RequestMapping("/ogg/do")
    @ResponseBody
    public Map Do(HttpServletRequest request) {
        String ip = request.getParameter("ip");
        String cmd = request.getParameter("cmd");
        Assert.hasText(ip, "com.winit.uCloud.web.UCloudCController.CleanReadis,ip为空");
        Assert.hasText(cmd, "com.winit.uCloud.web.UCloudCController.CleanReadis,cmd为空");

        Map map = new HashMap();
        try {
            map = uCloudCManager.runOggCmd(ip, cmd);
        } catch (Exception e) {
            map.put("code", "1");
            map.put("message", "执行命令异常." + e.getMessage());
            logger.error("com.winit.uCloud.web.UCloudCController.Do 异常 ip=" + ip + ",cmd=" + cmd, e);
        }
        logger.info("com.winit.uCloud.web.UCloudCController.Do rtn:" + map);
        return map;
    }
}
